package com.market2.session;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import com.market2.dto.AdministrateurDto;
import com.market2.model.Administrateur;
import com.market2.utils.EntityManagerThreadLocal;
import com.market2.utils.Globals;
import com.market2.utils.converter.ConverterUtil;

/**
 * Session Bean implementation class AdministrateurManager
 */

@Stateless @RemoteBinding(jndiBinding="Market2EAR/AdministrateurManager/remote")
public class AdministrateurManager implements AdministrateurManagerRemote
{
	@PersistenceContext(unitName=Globals.PERSISTENCE_UNIT_NAME)
	private EntityManager entityManager;
	
	@PostConstruct
	void init() {
		EntityManagerThreadLocal.set(entityManager);
	}
	
	@Override
	public List<AdministrateurDto> getAllAdministrateurs()
	{
		Query query = entityManager.createQuery("from Administrateur");
		
		@SuppressWarnings("unchecked")
		List<Administrateur> queryResult = query.getResultList();
		
		return ConverterUtil.convertTo(queryResult, AdministrateurDto.class);
	}

	@Override
	public void enregistrerAdministrateur(AdministrateurDto administrateur)
	{
		Administrateur admin = ConverterUtil.convertFrom(administrateur, Administrateur.class);
		entityManager.persist(admin);
		entityManager.flush();
	}
	
	@Override
	public AdministrateurDto getAdministrateurByLogin(String login)
	{
		Administrateur admin = entityManager.find(Administrateur.class, login);
		return ConverterUtil.convertTo(admin, AdministrateurDto.class);
	}
	
	@Override
	public Boolean checkLoginPassword(String login, String password)
	{
		Query query = entityManager.createQuery("from Investisseur inv where inv.login = :login and inv.password = :password");
		query.setParameter("login", login);
		query.setParameter("password", password);
		
		return query.getResultList().size() == 1;
	}
}
